#include "StrmBMP_writer.h"
#include <filesystem>

StrmBMP_writer::StrmBMP_writer(std::string OutputPath)
{
  oFile.open(OutputPath,std::ios::binary);
  if(!oFile.is_open())
    throw std::logic_error("无法输出文件");
}

StrmBMP_writer::~StrmBMP_writer()
{
  if(oFile.is_open())
    oFile.close();
}

fileHead* StrmBMP_writer::getFileHead()
{
  return &FileHead;
}

void StrmBMP_writer::BeginInput(uint32_t width,uint32_t height,int16_t channel)
{
  imageIndex=1;
  additionalList.clear();
  oFile.seekp(2048,std::ios::beg);
  FileHead.imageWidth=width;
  FileHead.imageHeight=height;
  FileHead.pixelType=channel;
}

void StrmBMP_writer::AddImage(char* imageData,uint64_t Time)
{
  imageBlockHead blockHead={imageIndex,Time};
  oFile.write((char*)&blockHead,sizeof(imageBlockHead));
  oFile.write(imageData,FileHead.imageHeight*FileHead.imageWidth);
  if(!oFile.good())
    throw std::runtime_error("文件存储失败");
  imageIndex++;
}

void StrmBMP_writer::AddAdditional(int16_t value,uint64_t time)
{
  additionalList.push_back({time,value});
}

void StrmBMP_writer::EndInput()
{
  long pos=oFile.tellp();
  FileHead.imageDataBlockLength=pos-2048;
  for(const additionalBlockHead& i : additionalList)
  {
    oFile.write((char*)&i,sizeof(additionalBlockHead));
  }
  pos=oFile.tellp();
  FileHead.additionalBlockLength=pos-FileHead.imageDataBlockLength;
  oFile.seekp(0,std::ios::beg);
  oFile.write((char*)&FileHead,sizeof(fileHead));
  oFile.close();
}
